<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="https://img.picui.cn/free/2024/10/08/67052d608221c.png" type="image/png">
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .tabular-nums {
            font-variant-numeric: tabular-nums;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }
        @keyframes scaleIn {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        @keyframes scaleOut {
            from { transform: scale(1); opacity: 1; }
            to { transform: scale(0.9); opacity: 0; }
        }
        @keyframes slideIn {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        @keyframes slideInLeft {
            from { transform: translateX(-100%); }
            to { transform: translateX(0); }
        }
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .dialog-backdrop {
            animation: fadeIn 0.3s ease-out forwards;
        }
        .dialog-backdrop.closing {
            animation: fadeOut 0.3s ease-in forwards;
        }
        .dialog-content {
            animation: scaleIn 0.3s ease-out forwards;
        }
        .dialog-content.closing {
            animation: scaleOut 0.3s ease-in forwards;
        }
        .custom-scrollbar::-webkit-scrollbar {
            width: 8px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        .lap-record {
            animation: slideIn 0.3s ease-out forwards;
            opacity: 0;
        }
        .slide-in-left {
            animation: slideInLeft 0.5s ease-out;
        }
        .fade-in-up {
            animation: fadeInUp 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }
        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }
        .fade-out {
            animation: fadeOut 0.3s ease-in-out;
        }
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        @keyframes modalFadeIn {
            from { opacity: 0; transform: scale(0.8); }
            to { opacity: 1; transform: scale(1); }
        }
        @keyframes modalFadeOut {
            from { opacity: 1; transform: scale(1); }
            to { opacity: 0; transform: scale(0.8); }
        }
        .modal-content {
            animation: modalFadeIn 0.3s ease-out;
        }
        .modal-content.closing {
            animation: modalFadeOut 0.3s ease-in;
        }
        @keyframes modalOverlayFadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes modalOverlayFadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }
        .modal-overlay {
            animation: modalOverlayFadeIn 0.3s ease-out;
        }
        .modal-overlay.closing {
            animation: modalOverlayFadeOut 0.3s ease-in;
        }
        .mode-content {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        @keyframes floatIn {
            from { 
                opacity: 0; 
                transform: translateY(20px);
            }
            to { 
                opacity: 1; 
                transform: translateY(0);
            }
        }
        .float-in {
            animation: floatIn 0.5s ease-out forwards;
        }
        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }
        .fade-out {
            animation: fadeOut 0.3s ease-out forwards;
        }
        .mode-selector {
            width: 200px;
            background-color: #fef9c3;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            height: 100%;
            animation: slideInLeft 0.5s ease-out;
        }
        .mode-selector h1 {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 1.5rem;
            text-align: left;  /* 改为左对齐 */
            padding-left: 1rem;  /* 添加左内边距，与按钮对齐 */
        }
        .mode-selector button {
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            border-radius: 0.75rem;
            transition: all 0.3s;
            font-size: 1.25rem;
            text-align: left;
            width: 100%;
            border: none;
            background: none;
            cursor: pointer;
        }
        .content-area {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f3f4f6;
        }
        @media (max-width: 768px) {
            .app-container {
                flex-direction: column;
            }
            .mode-selector {
                width: 100%;
                height: auto;
                flex-direction: row;
                overflow-x: auto;
                white-space: nowrap;
                padding: 0.5rem;
            }
            .mode-selector h1 {
                display: none;
            }
            .mode-selector button {
                display: inline-block;
                width: auto;
                margin-right: 0.5rem;
                padding: 0.5rem 1rem;
            }
            .mode-selector select {
                width: 100%; /* 增加选择宽度 */
                max-width: none; /* 移除最大宽度限制 */
                margin-top: 0.5rem; /* 添加一些上边距 */
            }
            .app-container {
                flex-direction: column;
            }
            .content-area {
                padding: 1rem;
            }
            .calculator-container {
                flex-direction: column;
                width: 100%;
                margin-left: 0;
                height: auto;
            }
            .calculator-main {
                width: 100%;
            }
            .calculator-history {
                width: 100%;
                margin-top: 1rem;
            }
        }
        @keyframes slideInLeft {
            from { transform: translateX(-100%); }
            to { transform: translateX(0); }
        }
        .app-container {
            display: flex;
            height: 100vh;
            width: 100vw;
        }
        .clock-time {
            font-size: 4rem;
        }
        .calculator-container {
            display: flex;
            flex-direction: row;
            max-width: 1000px; /* 增加计算器的最大宽度 */
            width: 100%;
        }
        .calculator-main {
            flex: 3; /* 增加主体部分的比例 */
            display: flex;
            flex-direction: column;
        }
        .calculator-history {
            flex: 2; /* 增加历分的比例 */
            margin-left: 1rem;
            display: flex;
            flex-direction: column;
            max-height: 400px;
        }
        .calculator-buttons {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .history-content {
            flex-grow: 1;
            overflow-y: auto; /* 添加垂直滚动 */
        }
        @media (max-width: 768px) {
            .calculator-container {
                flex-direction: column;
                max-width: 100%;
            }
            .calculator-main {
                width: 100%;
            }
            .calculator-history {
                width: 100%;
                margin-left: 0;
                margin-top: 1rem;
            }
            .content-area {
                padding: 1rem;
            }
            .mode-selector {
                width: 100%;
                height: auto;
                flex-direction: row;
                overflow-x: auto;
                white-space: nowrap;
                padding: 0.5rem;
            }
            .mode-selector h1 {
                display: none;
            }
            .mode-selector button {
                display: inline-block;
                width: auto;
                margin-right: 0.5rem;
                padding: 0.5rem 1rem;
            }
        }
        .calculator-wide {
            max-width: 1000px; /* 增加计算器的最大宽度 */
            width: 100%;
        }
        
        .calculator-wide .calculator-main {
            flex: 3; /* 增加主体部分的比例 */
        }
        
        .calculator-wide .calculator-history {
            flex: 2; /* 增加历史记录部分的比例 */
        }
        
        @media (max-width: 768px) {
            .calculator-wide {
                max-width: 100%;
            }
            .calculator-wide .calculator-main,
            .calculator-wide .calculator-history {
                width: 100%;
            }
        }
        .content-area {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f3f4f6;
            padding: 1rem;
        }
        .component-container {
            width: 100%;
            max-width: 600px; /* 默认最大宽度 */
            margin: 0 auto; /* 居中显示 */
        }
        .component-container.narrow {
            max-width: 400px; /* 秒表和计时器的较窄宽度 */
        }
        .calculator-wide {
            max-width: 1000px; /* 计算器的最宽度 */
        }
        @media (max-width: 768px) {
            .component-container,
            .calculator-wide {
                max-width: 100%;
            }
        }
        @keyframes scaleIn {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }
        .scale-in {
            animation: scaleIn 0.3s ease-out;
        }
        .calendar-container {
            transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
        }
        .fade-prev {
            animation: fadePrev 0.6s ease-in-out;
        }
        .fade-next {
            animation: fadeNext 0.6s ease-in-out;
        }
        @keyframes fadePrev {
            0% { opacity: 1; transform: translateX(0); }
            50% { opacity: 0; transform: translateX(20px); }
            51% { opacity: 0; transform: translateX(-20px); }
            100% { opacity: 1; transform: translateX(0); }
        }
        @keyframes fadeNext {
            0% { opacity: 1; transform: translateX(0); }
            50% { opacity: 0; transform: translateX(-20px); }
            51% { opacity: 0; transform: translateX(20px); }
            100% { opacity: 1; transform: translateX(0); }
        }
        @keyframes popIn {
            0% { transform: scale(0.8); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }

        .animate-pop-in {
            animation: popIn 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55) forwards;
        }

        /* 主题样式 */
        .theme-default {
            background-color: #f3f4f6;  /* 整体背景色 */
            color: #1f2937;  /* 默认文字颜色 */
        }

        .theme-default .mode-selector {
            background-color: #fef9c3;  /* 左侧工具栏背景色 */
        }

        .theme-default .content-area {
            background-color: #f3f4f6;  /* 主内容区背景色 */
        }

        .theme-default .bg-yellow-50 {
            background-color: #fffbeb;  /* 时钟组件背景色 */
        }

        .theme-default .text-gray-800 {
            color: #1f2937;  /* 时钟文字颜色 */
        }

        .theme-default .text-gray-600 {
            color: #4b5563;  /* 日期文字颜色 */
        }

        .theme-default .bg-white {
            background-color: #ffffff;  /* 日历背景色 */
        }

        .theme-default .text-blue-500 {
            color: #3b82f6;  /* 蓝色文字和按钮 */
        }

        .theme-default .bg-blue-500 {
            background-color: #3b82f6;  /* 蓝色背景（当前日期） */
        }

        .theme-default .text-gray-500 {
            color: #6b7280;  /* 日历中的星期文字颜色 */
        }

        .theme-default .hover\:bg-gray-100:hover {
            background-color: #f3f4f6;  /* 日历中日期悬停效果 */
        }

        .theme-night {
            background-color: #1a1a1a;
            color: #e0e0e0; /* 调整为浅灰色,提高可读性 */
        }

        .theme-night .mode-selector {
            background-color: #2c2c2c;
        }

        .theme-night .content-area {
            background-color: #333333;
        }

        .theme-night .bg-white,
        .theme-night .bg-yellow-50 {
            background-color: #2c2c2c; /* 更深的灰色背景 */
            color: #e0e0e0;
        }

        .theme-night .text-gray-800,
        .theme-night .text-gray-600,
        .theme-night .text-gray-500 {
            color: #b0b0b0; /* 浅灰色字 */
        }

        .theme-night .bg-blue-500 {
            background-color: #3b82f6; /* 保持蓝色更明显 */
        }

        .theme-night .text-blue-500 {
            color: #60a5fa; /* 更亮的蓝色 */
        }

        /* 时钟样式调整 */
        .theme-night .clock-time {
            color: #60a5fa; /* 更亮的蓝色用于时间显示 */
        }

        .theme-night .text-5xl {
            text-shadow: 0 0 10px rgba(96, 165, 250, 0.5); /* 添加发光效果 */
        }

        /* 迷宫游戏样式调整（适用于所有主题） */
        .maze-cell {
            border: 1px solid rgba(255, 255, 255, 0.2); /* 半透明白色边框 */
        }

        .theme-default .maze-wall { background-color: #333333; }
        .theme-night .maze-wall { background-color: #000000; }
        .theme-fresh .maze-wall { background-color: #1e40af; }
        .theme-orange .maze-wall { background-color: #9a3412; }

        .theme-default .maze-path { background-color: #ffffff; }
        .theme-night .maze-path { background-color: #4a5568; }
        .theme-fresh .maze-path { background-color: #e0f2fe; }
        .theme-orange .maze-path { background-color: #fff7ed; }

        .theme-default .maze-player { background-color: #ef4444; }
        .theme-night .maze-player { background-color: #f87171; }
        .theme-fresh .maze-player { background-color: #ef4444; }
        .theme-orange .maze-player { background-color: #ef4444; }

        .theme-default .maze-end { background-color: #22c55e; }
        .theme-night .maze-end { background-color: #4ade80; }
        .theme-fresh .maze-end { background-color: #22c55e; }
        .theme-orange .maze-end { background-color: #22c55e; }

        .theme-fresh {
            background-color: #e6f3ff;
            color: #333333;
        }

        .theme-fresh .mode-selector {
            background-color: #b3d9ff;
        }

        .theme-fresh .content-area {
            background-color: #ffffff;
        }

        .theme-fresh .bg-white,
        .theme-fresh .bg-yellow-50 {
            background-color: #d1e8ff; /* 浅蓝色背景 */
        }

        .theme-fresh .bg-blue-500 {
            background-color: #3b82f6;
        }

        .theme-orange {
            background-color: #fff5e6;
            color: #333333;
        }

        .theme-orange .mode-selector {
            background-color: #ffd9b3;
        }

        .theme-orange .content-area {
            background-color: #ffffff;
        }

        .theme-orange .bg-white,
        .theme-orange .bg-yellow-50 {
            background-color: #ffe8cc; /* 浅橙色背景 */
        }

        .theme-orange .bg-blue-500 {
            background-color: #f97316; /* 橙色替代蓝色 */
        }

        .theme-orange .text-blue-500 {
            color: #ea580c; /* 深橙色文字 */
        }

        /* 为所有元素添加颜色和背景色的过渡效果 */
        * {
            transition: color 0.3s ease, background-color 0.3s ease;
        }

        /* 为特定元素添加更多细节的过渡效果 */
        .mode-selector,
        .content-area,
        .bg-white,
        .bg-yellow-50,
        .text-gray-800,
        .text-gray-600,
        .text-gray-500,
        .bg-blue-500,
        .text-blue-500 {
            transition: all 0.3s ease;
        }

        #loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            opacity: 1;
            transition: opacity 1s ease-out, visibility 2s ease-out;
            visibility: visible;
        }

        #loading.fade-out {
            opacity: 0;
            visibility: hidden;
        }

        #loading img {
            animation: rotate-pause 1.6s linear infinite;
        }

        @keyframes rotate-pause {
            0%, 25%, 50%, 75%, 100% { animation-timing-function: steps(1, end); }
            0% { transform: rotate(0deg); }
            25% { transform: rotate(90deg); }
            50% { transform: rotate(180deg); }
            75% { transform: rotate(270deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div id="root"></div>

    <div id="loading" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #fff; display: flex; justify-content: center; align-items: center; z-index: 9999; opacity: 1; transition: opacity 2s ease-out, visibility 2s ease-out; visibility: visible;">
        <img src="https://img.picui.cn/free/2024/10/08/67052d608221c.png" alt="加载中" style="animation: rotate-pause 1.6s linear infinite;">
    </div>

    <script>
        window.addEventListener('load', function() {
            var loading = document.getElementById('loading');
            var loadingImg = loading.querySelector('img');
            
            // 开始旋转动画
            loadingImg.style.animation = 'rotate-pause 1.6s linear infinite';
            
            setTimeout(function() {
                // 开始淡出效果
                loading.style.opacity = '0';
                loading.style.visibility = 'hidden';
                loading.addEventListener('transitionend', function() {
                    loading.style.display = 'none';
                });
            }, 3000); // 等待3秒后开始淡出，你可以根据需要调整这个时间
        });
    </script>

    <script type="text/babel">
        const { useState, useEffect, useCallback, useMemo, useRef } = React;

        function Button({ onClick, disabled, className, children }) {
            return (
                <button 
                    onClick={onClick} 
                    disabled={disabled}
                    className={`px-4 py-2 rounded-xl ${className}`}
                >
                    {children}
                </button>
            );
        }

        function ScrollArea({ children, shouldScrollToBottom }) {
            const scrollRef = useRef(null);

            useEffect(() => {
                if (shouldScrollToBottom && scrollRef.current) {
                    scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
                }
            }, [shouldScrollToBottom]);

            return (
                <div ref={scrollRef} className="h-40 w-full border rounded-xl bg-blue-200 p-2 overflow-auto custom-scrollbar">
                    {children}
                </div>
            );
        }

        function Dialog({ open, onOpenChange, children }) {
            const [isClosing, setIsClosing] = useState(false);

            useEffect(() => {
                if (!open) {
                    setIsClosing(false);
                }
            }, [open]);

            const closeWithAnimation = () => {
                setIsClosing(true);
                setTimeout(() => {
                    setIsClosing(false);
                    onOpenChange(false);
                }, 300);
            };

            if (!open && !isClosing) return null;

            return (
                <div className={`fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center dialog-backdrop ${isClosing ? 'closing' : ''}`}>
                    <div className={`bg-yellow-50 rounded-xl max-w-[300px] p-4 dialog-content ${isClosing ? 'closing' : ''}`}>
                        {typeof children === 'function' ? children({ onClose: closeWithAnimation }) : children}
                    </div>
                </div>
            );
        }

        function Stopwatch() {
            const [time, setTime] = useState(0);
            const [isRunning, setIsRunning] = useState(false);
            const [laps, setLaps] = useState([]);
            const [showJumpDialog, setShowJumpDialog] = useState(false);
            const [selectedLapTime, setSelectedLapTime] = useState(null);
            const [isClosing, setIsClosing] = useState(false);
            const intervalRef = useRef(null);

            useEffect(() => {
                if (isRunning) {
                    intervalRef.current = setInterval(() => {
                        setTime(prevTime => prevTime + 10);
                    }, 10);
                } else {
                    clearInterval(intervalRef.current);
                }
                return () => clearInterval(intervalRef.current);
            }, [isRunning]);

            const handleStartStop = () => {
                setIsRunning(!isRunning);
            };

            const handleReset = () => {
                setTime(0);
                setIsRunning(false);
                setLaps([]);
            };

            const handleLap = () => {
                setLaps(prevLaps => [...prevLaps, time]);
            };

            const handleDeleteLap = (index) => {
                setLaps(prevLaps => prevLaps.filter((_, i) => i !== index));
            };

            const handleLapClick = (lapTime) => {
                setSelectedLapTime(lapTime);
                setShowJumpDialog(true);
            };

            const handleJumpToTime = () => {
                if (selectedLapTime !== null) {
                    setTime(selectedLapTime);
                    setIsRunning(false);
                    setShowJumpDialog(false);
                }
            };

            const handleCloseDialog = () => {
                setIsClosing(true);
                setTimeout(() => {
                    setShowJumpDialog(false);
                    setIsClosing(false);
                }, 300);
            };

            const formatTime = (ms) => {
                const minutes = Math.floor(ms / 60000);
                const seconds = Math.floor((ms % 60000) / 1000);
                const centiseconds = Math.floor((ms % 1000) / 10);
                return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${centiseconds.toString().padStart(2, '0')}`;
            };

            return (
                <div className="bg-yellow-50 rounded-3xl shadow-lg p-9 space-y-6">
                    <div className="text-6xl font-mono font-bold text-gray-800 w-full text-center tabular-nums transition-all duration-100 ease-in-out bg-white p-6 rounded-xl shadow">
                        {formatTime(time)}
                    </div>
                    <div className="flex w-full space-x-3">
                        <Button 
                            onClick={handleStartStop}
                            className="flex-1 bg-blue-500 hover:bg-blue-600 text-white text-lg py-3"
                        >
                            {isRunning ? '停止' : '开始'}
                        </Button>
                        <Button 
                            onClick={handleLap}
                            disabled={!isRunning}
                            className="flex-1 bg-green-500 hover:bg-green-600 text-white text-lg py-3 disabled:opacity-50"
                        >
                            分段
                        </Button>
                        <Button 
                            onClick={handleReset}
                            className="flex-1 bg-red-500 hover:bg-red-600 text-white text-lg py-3"
                        >
                            重置
                        </Button>
                    </div>
                    {laps.length > 0 && (
                        <div className="w-full bg-white rounded-xl p-4 space-y-2 max-h-60 overflow-auto">
                            {laps.map((lapTime, index) => (
                                <div key={index} className="flex justify-between items-center">
                                    <span className="cursor-pointer hover:text-blue-600" onClick={() => handleLapClick(lapTime)}>
                                        第 {index + 1} 次: {formatTime(lapTime)}
                                    </span>
                                    <button
                                        onClick={() => handleDeleteLap(index)}
                                        className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 p-1 rounded transition duration-200"
                                    >
                                        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fillRule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
                                        </svg>
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                    {showJumpDialog && (
                        <div className={`modal-overlay ${isClosing ? 'closing' : ''}`}>
                            <div className={`modal-content bg-white p-8 rounded-xl shadow-lg w-80 flex flex-col items-center ${isClosing ? 'closing' : ''}`}>
                                <h2 className="text-2xl font-bold mb-4">确认转</h2>
                                <p className="text-center mb-6">
                                    是否要跳转到 {formatTime(selectedLapTime)} ?
                                </p>
                                <div className="flex space-x-4">
                                    <Button 
                                        onClick={handleCloseDialog}
                                        className="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded"
                                    >
                                        取消
                                    </Button>
                                    <Button 
                                        onClick={handleJumpToTime}
                                        className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
                                    >
                                        确认
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            );
        }

        function ModeSelector({ currentMode, onModeChange, currentTheme, onThemeChange }) {
            const modes = [
                { id: 'clock', name: '时间' },
                { id: 'stopwatch', name: '秒表' },
                { id: 'timer', name: '计时器' },
                { id: 'calculator', name: '计算器' },
                { id: 'writingpad', name: '写字板' },
                { id: 'game', name: '小游戏' },
                { id: 'randomnumber', name: '随机数' },  // 新增
            ];

            const themes = [
                { id: 'default', name: '默认' },
                { id: 'night', name: '夜间' },
                { id: 'fresh', name: '清爽' },
                { id: 'orange', name: '橙色' },
            ];

            return (
                <div className="mode-selector">
                    <h1>工具</h1>
                    {modes.map(mode => (
                        <button
                            key={mode.id}
                            onClick={() => onModeChange(mode.id)}
                            className={`w-full ${
                                currentMode === mode.id ? 'active bg-yellow-200 font-bold' : 'hover:bg-yellow-50'
                            }`}
                        >
                            {mode.name}
                        </button>
                    ))}
                    <div className="mt-auto">
                        <h2 className="text-lg font-bold mb-2 flex items-center">
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M4 2a2 2 0 00-2 2v11a3 3 0 106 0V4a2 2 0 00-2-2H4zm1 14a1 1 0 100-2 1 1 0 000 2zm5-1.757l4.9-4.9a2 2 0 000-2.828L13.485 5.1a2 2 0 00-2.828 0L10 5.757v8.486zM16 18H9.071l6-6H16a2 2 0 012 2v2a2 2 0 01-2 2z" clipRule="evenodd" />
                            </svg>
                            主题
                        </h2>
                        <select 
                            value={currentTheme} 
                            onChange={(e) => {
                                const newTheme = e.target.value;
                                // 添加一个短暂的延迟，让用户能看到过渡效果
                                setTimeout(() => onThemeChange(newTheme), 50);
                            }}
                            className="w-full p-2 rounded-md bg-white border border-gray-300"
                        >
                            {themes.map(theme => (
                                <option key={theme.id} value={theme.id}>
                                    {theme.name}
                                </option>
                            ))}
                        </select>
                    </div>
                </div>
            );
        }

        function Clock() {
            const [time, setTime] = useState(new Date());
            const [selectedDate, setSelectedDate] = useState(null);
            const [currentMonth, setCurrentMonth] = useState(new Date());
            const [isAnimating, setIsAnimating] = useState(false);
            const [animationDirection, setAnimationDirection] = useState('');

            useEffect(() => {
                const timer = setInterval(() => setTime(new Date()), 1000);
                return () => clearInterval(timer);
            }, []);

            const weekdays = ["日", "一", "二", "三", "四", "五", "六"];
            const months = ["一月", "二月", "三月", "四月", "月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];

            const holidays = {
                "1-1": "元旦",
                "5-1": "劳动节",
                "10-1": "国庆节",
                // 添加更多假日...
            };

            const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();

            const generateCalendar = (date) => {
                const year = date.getFullYear();
                const month = date.getMonth();
                const daysInMonth = getDaysInMonth(year, month);
                const firstDayOfMonth = new Date(year, month, 1).getDay();
                const calendar = [];

                for (let i = 0; i < firstDayOfMonth; i++) {
                    calendar.push(null);
                }

                for (let i = 1; i <= daysInMonth; i++) {
                    calendar.push(i);
                }

                return calendar;
            };

            const calendar = generateCalendar(currentMonth);

            const handleMonthChange = (direction) => {
                setIsAnimating(true);
                setAnimationDirection(direction);
                setTimeout(() => {
                    if (direction === 'prev') {
                        setCurrentMonth(prev => new Date(prev.getFullYear(), prev.getMonth() - 1, 1));
                    } else {
                        setCurrentMonth(prev => new Date(prev.getFullYear(), prev.getMonth() + 1, 1));
                    }
                    setIsAnimating(false);
                }, 300); // 动画持续时间的一半
            };

            const handlePrevMonth = () => {
                const now = new Date();
                const prevMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1);
                if (prevMonth >= new Date(now.getFullYear(), now.getMonth() - 1, 1)) {
                    handleMonthChange('prev');
                }
            };

            const handleNextMonth = () => {
                const now = new Date();
                const nextMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1);
                if (nextMonth <= new Date(now.getFullYear(), now.getMonth() + 1, 1)) {
                    handleMonthChange('next');
                }
            };

            const isPrevMonthDisabled = () => {
                const now = new Date();
                return currentMonth <= new Date(now.getFullYear(), now.getMonth() - 1, 1);
            };

            const isNextMonthDisabled = () => {
                const now = new Date();
                return currentMonth >= new Date(now.getFullYear(), now.getMonth() + 1, 1);
            };

            const handleDateClick = (day) => {
                if (day) {
                    const clickedDate = new Date(time.getFullYear(), time.getMonth(), day);
                    setSelectedDate(clickedDate);
                }
            };

            const getHoliday = (date) => {
                const key = `${date.getMonth() + 1}-${date.getDate()}`;
                return holidays[key] || null;
            };

            return (
                <div className="bg-yellow-50 rounded-3xl shadow-lg p-6 space-y-4">
                    <div className="flex flex-col items-center space-y-2 p-4 bg-[#FEFCE8] rounded-xl shadow">
                        <div className="text-5xl font-mono font-bold text-gray-800 tabular-nums">
                            {time.toLocaleTimeString()}
                        </div>
                        <div className="text-xl text-gray-600">
                            {time.getFullYear()}年{time.getMonth() + 1}月{time.getDate()}日 星期{weekdays[time.getDay()]}
                        </div>
                    </div>
                    <div className="bg-white rounded-xl p-4 shadow">
                        <div className="flex justify-between items-center mb-2">
                            <button 
                                onClick={handlePrevMonth} 
                                className={`text-blue-500 hover:text-blue-700 focus:outline-none transition duration-300 ease-in-out transform hover:scale-110 ${isPrevMonthDisabled() ? 'opacity-50 cursor-not-allowed' : ''}`}
                                disabled={isPrevMonthDisabled()}
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                </svg>
                            </button>
                            <div className="text-xl font-bold">
                                {months[currentMonth.getMonth()]} {currentMonth.getFullYear()}
                            </div>
                            <button 
                                onClick={handleNextMonth} 
                                className={`text-blue-500 hover:text-blue-700 focus:outline-none transition duration-300 ease-in-out transform hover:scale-110 ${isNextMonthDisabled() ? 'opacity-50 cursor-not-allowed' : ''}`}
                                disabled={isNextMonthDisabled()}
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                </svg>
                            </button>
                        </div>
                        <div className={`calendar-container ${isAnimating ? `fade-${animationDirection}` : ''}`}>
                            <div className="grid grid-cols-7 gap-1">
                                {weekdays.map(day => (
                                    <div key={day} className="text-center text-gray-500 text-sm">{day}</div>
                                ))}
                                {generateCalendar(currentMonth).map((day, index) => (
                                    <div 
                                        key={index} 
                                        className={`text-center p-1 cursor-pointer ${
                                            day === time.getDate() && 
                                            currentMonth.getMonth() === time.getMonth() && 
                                            currentMonth.getFullYear() === time.getFullYear() 
                                                ? 'bg-blue-500 text-white rounded-full' 
                                                : day ? 'hover:bg-gray-100' : ''
                                        }`}
                                        onClick={() => day && handleDateClick(day)}
                                    >
                                        {day}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                    {selectedDate && (
                        <div className="bg-white rounded-xl p-4 shadow fade-in-up">
                            <h3 className="text-lg font-bold mb-2">
                                {selectedDate.getFullYear()}年{selectedDate.getMonth() + 1}月{selectedDate.getDate()}日
                            </h3>
                            <p>星期{weekdays[selectedDate.getDay()]}</p>
                            {getHoliday(selectedDate) && (
                                <p className="text-red-500">{getHoliday(selectedDate)}</p>
                            )}
                            <a 
                                href="https://www.msn.cn/zh-cn/weather/forecast/in-%E4%B8%8A%E6%B5%B7%E5%B8%82,%E5%AE%9D%E5%B1%B1%E5%8C%BA" 
                                target="_blank" 
                                rel="noopener noreferrer"
                                className="mt-2 inline-block bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
                            >
                                查看天气
                            </a>
                        </div>
                    )}
                </div>
            );
        }

        function Timer() {
            const [minutes, setMinutes] = useState(0);
            const [seconds, setSeconds] = useState(0);
            const [isRunning, setIsRunning] = useState(false);
            const [timeLeft, setTimeLeft] = useState(0);
            const [showAlert, setShowAlert] = useState(false);
            const [isClosing, setIsClosing] = useState(false);
            const audioRef = useRef(null);

            useEffect(() => {
                let interval;
                if (isRunning && timeLeft > 0) {
                    interval = setInterval(() => {
                        setTimeLeft((prevTime) => Math.max(0, prevTime - 1));
                    }, 1000);
                } else if (timeLeft === 0 && isRunning) {
                    setIsRunning(false);
                    setShowAlert(true);
                    audioRef.current.play();
                }
                return () => clearInterval(interval);
            }, [isRunning, timeLeft]);

            const handleStart = () => {
                const totalSeconds = minutes * 60 + seconds;
                if (totalSeconds > 0) {
                    setTimeLeft(totalSeconds);
                    setIsRunning(true);
                }
            };

            const handleReset = () => {
                setIsRunning(false);
                setTimeLeft(0);
                setMinutes(0);
                setSeconds(0);
            };

            const handleCloseAlert = () => {
                setIsClosing(true);
                setTimeout(() => {
                    setShowAlert(false);
                    setIsClosing(false);
                    audioRef.current.pause();
                    audioRef.current.currentTime = 0;
                }, 300);
            };

            const formatTime = (time) => {
                const mins = Math.floor(time / 60);
                const secs = time % 60;
                return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            };

            return (
                <div className="bg-yellow-50 rounded-3xl shadow-lg p-9 space-y-6">
                    <div className="text-6xl font-mono font-bold text-gray-800 w-full text-center tabular-nums transition-all duration-100 ease-in-out bg-white p-6 rounded-xl shadow">
                        {isRunning ? formatTime(timeLeft) : formatTime(minutes * 60 + seconds)}
                    </div>
                    {!isRunning && (
                        <div className="flex space-x-4 items-center justify-center">
                            <label className="text-lg">分:</label>
                            <input
                                type="number"
                                value={minutes}
                                onChange={(e) => setMinutes(Math.max(0, parseInt(e.target.value) || 0))}
                                className="w-20 p-2 text-2xl text-center border rounded"
                                placeholder="00"
                            />
                            <label className="text-lg">秒:</label>
                            <input
                                type="number"
                                value={seconds}
                                onChange={(e) => setSeconds(Math.max(0, Math.min(59, parseInt(e.target.value) || 0)))}
                                className="w-20 p-2 text-2xl text-center border rounded"
                                placeholder="00"
                            />
                        </div>
                    )}
                    <div className="flex w-full space-x-3">
                        <Button 
                            onClick={isRunning ? () => setIsRunning(false) : handleStart}
                            className="flex-1 bg-blue-500 hover:bg-blue-600 text-white text-lg py-3"
                        >
                            {isRunning ? '暂停' : '开始'}
                        </Button>
                        <Button 
                            onClick={handleReset}
                            className="flex-1 bg-red-500 hover:bg-red-600 text-white text-lg py-3"
                        >
                            重置
                        </Button>
                    </div>
                    {showAlert && (
                        <div className={`modal-overlay ${isClosing ? 'closing' : ''}`}>
                            <div className={`modal-content bg-white p-8 rounded-xl shadow-lg w-80 flex flex-col items-center ${isClosing ? 'closing' : ''}`}>
                                <h2 className="text-3xl font-bold mb-6 text-center">时间到!</h2>
                                <Button 
                                    onClick={handleCloseAlert}
                                    className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 text-xl rounded-full"
                                >
                                    知道了
                                </Button>
                            </div>
                        </div>
                    )}
                    <audio ref={audioRef} src="https://www.soundjay.com/misc/sounds/bell-ringing-05.mp3" />
                </div>
            );
        }

        function Calculator() {
            const [display, setDisplay] = useState('0');
            const [memory, setMemory] = useState(null);
            const [operator, setOperator] = useState(null);
            const [waitingForOperand, setWaitingForOperand] = useState(true);
            const [history, setHistory] = useState([]);
            const [currentInput, setCurrentInput] = useState('');
            const [fontSize, setFontSize] = useState(28); // 初始字体大小
            const displayRef = useRef(null);
            const [errorMessage, setErrorMessage] = useState('');
            const MAX_INPUT_LENGTH = 16; // 设置最大输入长度
            const [fullExpression, setFullExpression] = useState('');

            const formatNumber = (num) => {
                if (num.length > MAX_INPUT_LENGTH) {
                    return Number(num).toExponential(MAX_INPUT_LENGTH - 6); // 6是为了 e+xxx 预留的空间
                }
                return num;
            };

            const isInputAllowed = (input) => {
                return input.length < MAX_INPUT_LENGTH;
            };

            const inputDigit = (digit) => {
                if (isInputAllowed(currentInput + digit)) {
                    if (waitingForOperand) {
                        setCurrentInput(String(digit));
                        setDisplay(String(digit));
                        setWaitingForOperand(false);
                    } else {
                        setCurrentInput(prevInput => prevInput + digit);
                        setDisplay(formatNumber(parseFloat(currentInput + digit)));
                    }
                    setFullExpression(prevExpr => prevExpr + digit);
                    setErrorMessage('');
                } else {
                    setErrorMessage('已达到最大输入长度');
                }
            };

            const inputDot = () => {
                if (isInputAllowed(currentInput + '.')) {
                    if (waitingForOperand) {
                        setCurrentInput('0.');
                        setDisplay('0.');
                        setWaitingForOperand(false);
                    } else if (currentInput.indexOf('.') === -1) {
                        setCurrentInput(prevInput => prevInput + '.');
                        setDisplay(currentInput + '.');
                    }
                    setFullExpression(prevExpr => prevExpr + '.');
                    setErrorMessage('');
                } else {
                    setErrorMessage('已达到最大输入长度');
                }
            };

            const performOperation = (nextOperator) => {
                const inputValue = parseFloat(currentInput);

                if (memory === null) {
                    setMemory(inputValue);
                } else if (operator) {
                    const currentValue = memory || 0;
                    let newValue;
                    switch (operator) {
                        case '+': newValue = currentValue + inputValue; break;
                        case '-': newValue = currentValue - inputValue; break;
                        case '×': newValue = currentValue * inputValue; break;
                        case '÷': newValue = currentValue / inputValue; break;
                        default: newValue = inputValue;
                    }
                    const formattedValue = formatNumber(String(newValue));
                    setMemory(parseFloat(formattedValue));
                    setDisplay(formattedValue);
                    
                    if (nextOperator === '=') {
                        const completeExpression = `${fullExpression} = ${formattedValue}`;
                        setHistory(prevHistory => [...prevHistory, completeExpression]);
                        setFullExpression('');
                    } else {
                        setFullExpression(formattedValue);
                    }
                    
                    setCurrentInput(formattedValue);
                }

                setWaitingForOperand(true);
                setOperator(nextOperator);
                if (nextOperator !== '=') {
                    setFullExpression(prevExpr => prevExpr + ' ' + nextOperator + ' ');
                    setCurrentInput('');
                } else {
                    setMemory(null);
                    setOperator(null);
                }
            };

            const clearDisplay = () => {
                setDisplay('0');
                setCurrentInput('');
                setWaitingForOperand(true);
                setMemory(null);
                setOperator(null);
                setFullExpression('');
            };

            const clearHistory = () => {
                setHistory([]);
            };

            // 加键盘件处理函数
            const handleKeyDown = (event) => {
                if (isInputAllowed(display)) {
                    event.preventDefault();
                    const key = event.key;

                    if (/[0-9]/.test(key)) {
                        inputDigit(parseInt(key, 10));
                    } else if (key === '.') {
                        inputDot();
                    } else if (['+', '-', '*', '/', 'x', '×'].includes(key)) {
                        let operator = key;
                        if (key === '*' || key === 'x') operator = '×';
                        if (key === '/') operator = '÷';
                        performOperation(operator);
                    } else if (key === 'Enter' || key === '=') {
                        performOperation('=');
                    } else if (key === 'Backspace') {
                        // 实现退格功能
                        if (!waitingForOperand) {
                            setDisplay(display.slice(0, -1) || '0');
                            setCurrentInput(currentInput.slice(0, -1));
                            if (display.length === 1) {
                                setWaitingForOperand(true);
                            }
                        }
                    } else if (key === 'Escape') {
                        clearDisplay();
                    }
                } else if (event.key === 'Backspace') {
                    // 允许退格键
                    if (!waitingForOperand) {
                        setDisplay(display.slice(0, -1) || '0');
                        setCurrentInput(currentInput.slice(0, -1));
                        if (display.length === 1) {
                            setWaitingForOperand(true);
                        }
                    }
                }
            };

            // 组件挂载和卸载时添加/移除事件监听器
            React.useEffect(() => {
                window.addEventListener('keydown', handleKeyDown);
                return () => {
                    window.removeEventListener('keydown', handleKeyDown);
                };
            }, [display, currentInput, waitingForOperand]); // 添加依赖项

            const buttons = [
                ['7', '8', '9', '÷'],
                ['4', '5', '6', '×'],
                ['1', '2', '3', '-'],
                ['0', '.', '=', '+'],
            ];

            return (
                <div className="bg-yellow-50 rounded-3xl shadow-lg p-6 calculator-container calculator-wide">
                    <div className="calculator-main">
                        <div className="font-mono font-bold text-gray-800 w-full text-left tabular-nums transition-all duration-500 ease-in-out bg-white p-4 rounded-xl shadow mb-4" style={{minHeight: '90px'}}>
                            <div className="text-lg text-gray-600 overflow-x-auto whitespace-nowrap">{fullExpression}</div>
                            <div className="text-4xl mt-2 overflow-hidden">
                                <span>{display}</span>
                            </div>
                            {errorMessage && <div className="text-red-500 text-sm mt-1">{errorMessage}</div>}
                        </div>
                        <div className="calculator-buttons">
                            <div className="grid grid-cols-4 gap-2 flex-grow">
                                {buttons.map((row, rowIndex) => (
                                    row.map((button, colIndex) => (
                                        <Button
                                            key={`${rowIndex}-${colIndex}`}
                                            onClick={() => {
                                                switch (button) {
                                                    case '=': performOperation('='); break;
                                                    case '+': case '-': case '×': case '÷': performOperation(button); break;
                                                    case '.': inputDot(); break;
                                                    default: inputDigit(parseInt(button, 10));
                                                }
                                            }}
                                            className={`text-xl py-3 transition-all duration-300 ease-in-out ${colIndex === 3 ? 'bg-yellow-200' : 'bg-white'}`}
                                        >
                                            {button}
                                        </Button>
                                    ))
                                ))}
                            </div>
                            <div className="grid grid-cols-4 gap-2 mt-2">
                                <Button
                                    onClick={clearDisplay}
                                    className="text-xl py-3 bg-yellow-300"
                                >
                                    归零
                                </Button>
                                <Button
                                    onClick={clearHistory}
                                    className="text-xl py-3 bg-yellow-300 col-span-3"
                                >
                                    清除历史记录
                                </Button>
                            </div>
                        </div>
                    </div>
                    <div className="calculator-history">
                        <h3 className="text-xl font-bold mb-2">历史记录</h3>
                        <div className="bg-white rounded-xl p-4 history-content custom-scrollbar">
                            {history.map((item, index) => (
                                <div 
                                    key={index} 
                                    className="cursor-pointer hover:bg-gray-100 p-2 rounded mb-1 text-sm"
                                    onClick={() => {
                                        const result = item.split('=')[1].trim();
                                        setDisplay(result);
                                        setMemory(parseFloat(result));
                                        setOperator(null);
                                        setWaitingForOperand(true);
                                        setCurrentInput(result);
                                        setFullExpression(result);
                                    }}
                                >
                                    {item}
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            );
        }

        function WritingPad() {
            const canvasRef = useRef(null);
            const containerRef = useRef(null);
            const [isDrawing, setIsDrawing] = useState(false);
            const [tool, setTool] = useState('pen'); // 'pen', 'eraser', 或 'line'
            const [color, setColor] = useState('#3B82F6');
            const [penSize, setPenSize] = useState(4); // 调整默认笔宽为4
            const [eraserSize, setEraserSize] = useState(36); // 调整默认橡皮宽度为36
            const [showSettings, setShowSettings] = useState(true);
            const [points, setPoints] = useState([]);
            const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });
            const [cursorVisible, setCursorVisible] = useState(false);
            const [lineStart, setLineStart] = useState(null);
            const [tempCanvas, setTempCanvas] = useState(null);
            const [mainCanvas, setMainCanvas] = useState(null);
            const [images, setImages] = useState([]);

            useEffect(() => {
                const canvas = canvasRef.current;
                const context = canvas.getContext('2d');
                
                // 设置画布尺寸为容器的实际尺寸
                const resizeCanvas = () => {
                    const container = containerRef.current;
                    canvas.width = container.clientWidth;
                    canvas.height = container.clientHeight;
                    context.lineCap = 'round';
                    context.lineJoin = 'round';
                    
                    // 填充白色背景
                    context.fillStyle = 'white';
                    context.fillRect(0, 0, canvas.width, canvas.height);

                    // 创建临时画布和主画布
                    const tempCanvasElement = document.createElement('canvas');
                    tempCanvasElement.width = canvas.width;
                    tempCanvasElement.height = canvas.height;
                    setTempCanvas(tempCanvasElement);

                    const mainCanvasElement = document.createElement('canvas');
                    mainCanvasElement.width = canvas.width;
                    mainCanvasElement.height = canvas.height;
                    const mainContext = mainCanvasElement.getContext('2d');
                    mainContext.fillStyle = 'white';
                    mainContext.fillRect(0, 0, mainCanvasElement.width, mainCanvasElement.height);
                    setMainCanvas(mainCanvasElement);
                };

                resizeCanvas();
                window.addEventListener('resize', resizeCanvas);

                return () => window.removeEventListener('resize', resizeCanvas);
            }, []);

            const getMousePos = (e) => {
                const canvas = canvasRef.current;
                const rect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                const x = ((e.clientX || e.touches[0].clientX) - rect.left) * scaleX;
                const y = ((e.clientY || e.touches[0].clientY) - rect.top) * scaleY;
                return { x, y };
            };

            const handleMouseMove = (e) => {
                const { x, y } = getMousePos(e);
                setCursorPosition({ x, y });
                if (isDrawing) {
                    draw(e);
                }
            };

            const startDrawing = (e) => {
                const { x, y } = getMousePos(e);
                if (tool === 'line') {
                    setLineStart({ x, y });
                } else {
                    setPoints([{ x, y }]);
                }
                setIsDrawing(true);
            };

            const draw = (e) => {
                if (!isDrawing) return;
                
                const { x, y } = getMousePos(e);
                
                if (tool === 'line') {
                    const canvas = canvasRef.current;
                    const context = canvas.getContext('2d');
                    const tempContext = tempCanvas.getContext('2d');

                    // 清除临时画布
                    tempContext.clearRect(0, 0, tempCanvas.width, tempCanvas.height);
                    
                    // 在临时画布上绘制新线条
                    tempContext.beginPath();
                    tempContext.moveTo(lineStart.x, lineStart.y);
                    tempContext.lineTo(x, y);
                    tempContext.strokeStyle = color;
                    tempContext.lineWidth = penSize;
                    tempContext.stroke();

                    // 清除主画布
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    
                    // 重新绘制主画布内容
                    context.drawImage(mainCanvas, 0, 0);
                    
                    // 绘制新的预览线
                    context.drawImage(tempCanvas, 0, 0);
                } else {
                    setPoints(prevPoints => [...prevPoints, { x, y }]);
                    
                    const canvas = canvasRef.current;
                    const context = canvas.getContext('2d');
                    const mainContext = mainCanvas.getContext('2d');
                    
                    context.strokeStyle = mainContext.strokeStyle = tool === 'eraser' ? 'white' : color;
                    context.lineWidth = mainContext.lineWidth = tool === 'eraser' ? eraserSize : penSize;
                    
                    // 使用贝塞尔曲线绘制平滑线条
                    if (points.length > 2) {
                        const lastTwoPoints = points.slice(-2);
                        const controlPoint = lastTwoPoints[0];
                        const endPoint = {
                            x: (lastTwoPoints[1].x + x) / 2,
                            y: (lastTwoPoints[1].y + y) / 2
                        };
                        
                        context.beginPath();
                        context.moveTo(lastTwoPoints[0].x, lastTwoPoints[0].y);
                        context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                        context.stroke();

                        mainContext.beginPath();
                        mainContext.moveTo(lastTwoPoints[0].x, lastTwoPoints[0].y);
                        mainContext.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                        mainContext.stroke();
                    }
                }
            };

            const stopDrawing = () => {
                if (tool === 'line' && isDrawing) {
                    const mainContext = mainCanvas.getContext('2d');
                    const { x, y } = cursorPosition;
                    mainContext.beginPath();
                    mainContext.moveTo(lineStart.x, lineStart.y);
                    mainContext.lineTo(x, y);
                    mainContext.strokeStyle = color;
                    mainContext.lineWidth = penSize;
                    mainContext.stroke();

                    // 更新主画布显示
                    const canvas = canvasRef.current;
                    const context = canvas.getContext('2d');
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.drawImage(mainCanvas, 0, 0);

                    // 清除临时画布
                    const tempContext = tempCanvas.getContext('2d');
                    tempContext.clearRect(0, 0, tempCanvas.width, tempCanvas.height);
                }
                setIsDrawing(false);
                setPoints([]);
                setLineStart(null);
            };

            const clearCanvas = () => {
                const canvas = canvasRef.current;
                const context = canvas.getContext('2d');
                context.fillStyle = 'white';
                context.fillRect(0, 0, canvas.width, canvas.height);
            };

            const saveImage = () => {
                const canvas = canvasRef.current;
                const context = canvas.getContext('2d');
                
                // 保存当前的画布状态
                context.save();
                
                // 创建一个临时画布
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = canvas.width;
                tempCanvas.height = canvas.height;
                const tempContext = tempCanvas.getContext('2d');
                
                // 在临时画布上绘制白色背景
                tempContext.fillStyle = 'white';
                tempContext.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
                
                // 将原画布的内容��制到临时画布上
                tempContext.drawImage(canvas, 0, 0);
                
                // 从临时画布生成图片
                const image = tempCanvas.toDataURL('image/png');
                
                // 恢复原画布的状态
                context.restore();
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = image;
                link.download = 'LToolBox_Drawing.png';
                link.click();
            };

            const renderCursor = () => {
                if (tool === 'eraser' && cursorVisible) {
                    const canvas = canvasRef.current;
                    const rect = canvas.getBoundingClientRect();
                    const scaleX = canvas.width / rect.width;
                    const scaleY = canvas.height / rect.height;
                    
                    return (
                        <div 
                            style={{
                                position: 'absolute',
                                left: (cursorPosition.x / scaleX) - (eraserSize / 2 / scaleX),
                                top: (cursorPosition.y / scaleY) - (eraserSize / 2 / scaleY),
                                width: eraserSize / scaleX,
                                height: eraserSize / scaleY,
                                borderRadius: '50%',
                                backgroundColor: 'rgba(173, 216, 230, 0.5)',
                                pointerEvents: 'none',
                            }}
                        />
                    );
                }
                return null;
            };

            const handleImageUpload = (event) => {
                const file = event.target.files[0];
                if (file && file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const img = new Image();
                        img.onload = () => {
                            const canvas = canvasRef.current;
                            const context = canvas.getContext('2d');
                            const mainContext = mainCanvas.getContext('2d');
                            
                            // 在画布中心绘制图片
                            const x = (canvas.width - img.width) / 2;
                            const y = (canvas.height - img.height) / 2;
                            context.drawImage(img, x, y);
                            mainContext.drawImage(img, x, y);
                            
                            setImages([...images, { img, x, y }]);
                        };
                        img.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            };

            return (
                <div className="bg-[#FFF9E5] rounded-3xl shadow-lg p-6">
                    <div className="flex flex-col md:flex-row">
                        <div 
                            ref={containerRef} 
                            className="flex-grow mr-0 md:mr-4 mb-4 md:mb-0 relative" 
                            style={{height: '500px'}}
                            onMouseEnter={() => setCursorVisible(true)}
                            onMouseLeave={() => setCursorVisible(false)}
                        >
                            <canvas
                                ref={canvasRef}
                                onMouseDown={startDrawing}
                                onMouseMove={handleMouseMove}
                                onMouseUp={stopDrawing}
                                onMouseOut={stopDrawing}
                                onTouchStart={startDrawing}
                                onTouchMove={handleMouseMove}
                                onTouchEnd={stopDrawing}
                                className="bg-white rounded-xl shadow w-full h-full"
                                style={{touchAction: 'none'}}
                            />
                            {renderCursor()}
                        </div>
                        <div className="w-full md:w-64 bg-green-100 rounded-xl p-4 flex flex-col">
                            <h3 className="text-lg font-bold mb-2">颜色</h3>
                            <input 
                                type="color" 
                                value={color} 
                                onChange={(e) => setColor(e.target.value)} 
                                className="w-full h-8 mb-4"
                            />
                            <h3 className="text-lg font-bold mb-2">笔粗细</h3>
                            <input 
                                type="range" 
                                min="1" 
                                max="20"
                                value={penSize} 
                                onChange={(e) => setPenSize(parseInt(e.target.value))} 
                                className="w-full mb-4"
                            />
                            <h3 className="text-lg font-bold mb-2">橡皮粗细</h3>
                            <input 
                                type="range" 
                                min="1" 
                                max="144"
                                value={eraserSize} 
                                onChange={(e) => setEraserSize(parseInt(e.target.value))} 
                                className="w-full mb-4"
                            />
                            <div className="flex flex-col space-y-2 mt-4">
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        checked={tool === 'pen'}
                                        onChange={() => setTool('pen')}
                                        className="form-radio h-5 w-5 text-blue-600"
                                    />
                                    <span className="ml-2 text-gray-700">笔</span>
                                </label>
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        checked={tool === 'eraser'}
                                        onChange={() => setTool('eraser')}
                                        className="form-radio h-5 w-5 text-blue-600"
                                    />
                                    <span className="ml-2 text-gray-700">橡皮</span>
                                </label>
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        checked={tool === 'line'}
                                        onChange={() => setTool('line')}
                                        className="form-radio h-5 w-5 text-blue-600"
                                    />
                                    <span className="ml-2 text-gray-700">直线</span>
                                </label>
                                <button 
                                    onClick={clearCanvas}
                                    className="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded mt-2"
                                >
                                    清除
                                </button>
                                <label 
                                    htmlFor="imageUpload"
                                    className="bg-[#22C55E] hover:bg-[#1ea34d] text-white px-4 py-2 rounded cursor-pointer text-center"
                                >
                                    插入图片
                                </label>
                                <input 
                                    id="imageUpload"
                                    type="file" 
                                    accept="image/*" 
                                    onChange={handleImageUpload} 
                                    className="hidden"
                                />
                                <button 
                                    onClick={saveImage}
                                    className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
                                >
                                    保存图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            );
        }


        function Game() {
            const [selectedGame, setSelectedGame] = useState(null);
            const [isTransitioning, setIsTransitioning] = useState(false);

            const games = [
                { id: 'maze', name: '迷宫', color: 'text-blue-500', icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M4 4h4v4H4zM12 4h4v4h-4zM20 4v4h-4V4zM4 12h4v4H4zM16 12v4h-4v-4zM20 12v4h-4v-4z" />
                    </svg>
                ) },
                { id: 'tictactoe', name: '井字棋', color: 'text-red-500', icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M3 3h18v18H3zM3 9h18M3 15h18M9 3v18M15 3v18" />
                        <path d="M7 7l4 4M11 7l-4 4M17 17l-4-4M13 17l4-4" strokeLinecap="round" />
                    </svg>
                ) },
                { id: 'DinosaurGame', name: '恐龙跳一跳', color: 'text-green-500', icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <rect x="2" y="2" width="8" height="8" />
                        <rect x="10" y="2" width="4" height="4" />
                        <rect x="14" y="2" width="4" height="4" />
                        <rect x="10" y="6" width="4" height="4" />
                        <rect x="2" y="14" width="4" height="4" />
                        <rect x="6" y="14" width="4" height="4" />
                        <rect x="10" y="14" width="4" height="4" />
                    </svg>
                ) },
                { id: 'whackamole', name: '打地鼠', color: 'text-purple-500', icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <circle cx="12" cy="12" r="10" />
                        <circle cx="12" cy="12" r="3" />
                        <line x1="12" y1="2" x2="12" y2="4" />
                        <line x1="12" y1="20" x2="12" y2="22" />
                        <line x1="2" y1="12" x2="4" y2="12" />
                        <line x1="20" y1="12" x2="22" y2="12" />
                    </svg>
                ) }
            ];

            const MazeGame = () => {
                const [playerPos, setPlayerPos] = useState({ x: 0, y: 0 });
                const [joystickPos, setJoystickPos] = useState({ x: 0, y: 0 });
                const mazeSize = 20;
                const [maze, setMaze] = useState([]);
                const [lastMoveTime, setLastMoveTime] = useState(0);
                const [showVictory, setShowVictory] = useState(false);
                const [debugMode, setDebugMode] = useState(false);
                const [debugPassword, setDebugPassword] = useState('');
                const [isMobile, setIsMobile] = useState(false);

                useEffect(() => {
                    generateMaze();
                    checkIfMobile();
                    window.addEventListener('resize', checkIfMobile);
                    return () => {
                        window.removeEventListener('resize', checkIfMobile);
                    };
                }, []);

                useEffect(() => {
                    const handleKeyDown = (event) => {
                        if (['w', 's', 'a', 'd'].includes(event.key.toLowerCase())) {
                            event.preventDefault();
                            switch (event.key.toLowerCase()) {
                                case 'w': movePlayer(0, -1); break;
                                case 's': movePlayer(0, 1); break;
                                case 'a': movePlayer(-1, 0); break;
                                case 'd': movePlayer(1, 0); break;
                            }
                        }
                    };

                    window.addEventListener('keydown', handleKeyDown);
                    return () => {
                        window.removeEventListener('keydown', handleKeyDown);
                    };
                }, [maze, debugMode]); // 添加 debugMode 作为依赖项

                const checkIfMobile = () => {
                    setIsMobile(window.innerWidth <= 768);
                };

                const generateMaze = () => {
                    let newMaze = Array(mazeSize).fill().map(() => Array(mazeSize).fill(1));
                    const stack = [{x: 0, y: 0}];
                    newMaze[0][0] = 0;

                    while (stack.length > 0) {
                        const current = stack[stack.length - 1];
                        const directions = [
                            {dx: 0, dy: -1}, {dx: 1, dy: 0}, {dx: 0, dy: 1}, {dx: -1, dy: 0}
                        ].sort(() => Math.random() - 0.5);

                        let moved = false;
                        for (const dir of directions) {
                            const nx = current.x + dir.dx * 2;
                            const ny = current.y + dir.dy * 2;
                            if (nx >= 0 && nx < mazeSize && ny >= 0 && ny < mazeSize && newMaze[ny][nx] === 1) {
                                newMaze[ny][nx] = 0;
                                newMaze[current.y + dir.dy][current.x + dir.dx] = 0;
                                stack.push({x: nx, y: ny});
                                moved = true;
                                break;
                            }
                        }

                        if (!moved) {
                            stack.pop();
                        }
                    }

                    // 使用 DFS 找到最远的可达点
                    const visited = Array(mazeSize).fill().map(() => Array(mazeSize).fill(false));
                    let farthestPoint = {x: 0, y: 0, distance: 0};

                    const dfs = (x, y, distance) => {
                        if (x < 0 || x >= mazeSize || y < 0 || y >= mazeSize || visited[y][x] || newMaze[y][x] === 1) {
                            return;
                        }

                        visited[y][x] = true;

                        if (distance > farthestPoint.distance) {
                            farthestPoint = {x, y, distance};
                        }

                        dfs(x + 1, y, distance + 1);
                        dfs(x - 1, y, distance + 1);
                        dfs(x, y + 1, distance + 1);
                        dfs(x, y - 1, distance + 1);
                    };

                    dfs(0, 0, 0);

                    // 设置终点
                    newMaze[farthestPoint.y][farthestPoint.x] = 2;

                    setMaze(newMaze);
                    setPlayerPos({ x: 0, y: 0 });
                    setShowVictory(false);
                };

                const movePlayer = (dx, dy) => {
                    const now = Date.now();
                    if (now - lastMoveTime < 100) return;

                    setPlayerPos(prevPos => {
                        const newX = prevPos.x + dx;
                        const newY = prevPos.y + dy;
                        if (newX >= 0 && newX < mazeSize && newY >= 0 && newY < mazeSize) {
                            if (debugMode || maze[newY][newX] !== 1) {
                                setLastMoveTime(now);
                                // 检查是否到点
                                if (maze[newY][newX] === 2) {
                                    setShowVictory(true);
                                }
                                return { x: newX, y: newY };
                            }
                        }
                        return prevPos;
                    });
                };

                const handleJoystickMove = (event) => {
                    const joystick = event.currentTarget.getBoundingClientRect();
                    const centerX = joystick.left + joystick.width / 2;
                    const centerY = joystick.top + joystick.height / 2;
                    const x = (event.clientX || event.touches[0].clientX) - centerX;
                    const y = (event.clientY || event.touches[0].clientY) - centerY;
                    const angle = Math.atan2(y, x);
                    const distance = Math.min(Math.sqrt(x*x + y*y), 25);
                    const newX = Math.cos(angle) * distance;
                    const newY = Math.sin(angle) * distance;
                    setJoystickPos({ x: newX, y: newY });

                    if (distance > 10) {
                        if (Math.abs(x) > Math.abs(y)) {
                            movePlayer(x > 0 ? 1 : -1, 0);
                } else {
                            movePlayer(0, y > 0 ? 1 : -1);
                        }
                    }
                };

                const handleJoystickEnd = () => {
                    setJoystickPos({ x: 0, y: 0 });
                };

                const handleDebugPasswordChange = (e) => {
                    setDebugPassword(e.target.value);
                };

                const toggleDebugMode = () => {
                    if (!debugMode) {
                        // 开启调试模式需要密码
                        if (debugPassword === '7878') {
                            setDebugMode(true);
                            setDebugPassword('');
                        }
                    } else {
                        // 关闭调试模式不需要密码
                        setDebugMode(false);
                    }
                };

                return (
                    <div className="flex flex-col items-center">
                        <div className="mb-4 bg-gray-200 p-2 rounded-lg" style={{ width: '300px', height: '300px' }}>
                            {maze.map((row, y) => (
                                <div key={y} className="flex" style={{ height: '5%' }}>
                                    {row.map((cell, x) => (
                                        <div 
                                            key={`${x}-${y}`} 
                                            className={`maze-cell
                                                ${cell === 1 ? 'maze-wall' : cell === 2 ? 'maze-end' : 'maze-path'}
                                                ${playerPos.x === x && playerPos.y === y ? 'maze-player' : ''}`}
                                            style={{ width: '5%', height: '100%' }}
                                        />
                                    ))}
                        </div>
                            ))}
                        </div>
                        {isMobile && (
                            <div 
                                className="w-32 h-32 bg-gray-300 rounded-full relative cursor-pointer mb-4"
                                onTouchStart={handleJoystickMove}
                                onTouchMove={handleJoystickMove}
                                onTouchEnd={handleJoystickEnd}
                            >
                                <div 
                                    className="w-16 h-16 bg-blue-500 rounded-full absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
                                    style={{
                                        transform: `translate(${joystickPos.x}px, ${joystickPos.y}px) translate(-50%, -50%)`
                                    }}
                                />
                            </div>
                        )}
                        <button onClick={generateMaze} className="mt-4 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition duration-300">
                            重新开始
                        </button>
                        <p className="mt-2 text-gray-600">
                            {isMobile ? '使用摇杆控制移动' : '使用 WSAD 键控制动'}
                        </p>
                        <div className="mt-4">
                            {!debugMode && (
                                <input 
                                    type="password" 
                                    value={debugPassword}
                                    onChange={handleDebugPasswordChange}
                                    placeholder="输入调试模式密码"
                                    className="px-2 py-1 border rounded mr-2"
                                />
                            )}
                            <button 
                                onClick={toggleDebugMode}
                                className={`px-4 py-2 rounded ${debugMode ? 'bg-red-500' : 'bg-blue-500'} text-white`}
                            >
                                {debugMode ? '关闭调试模式' : '开启调试模式'}
                        </button>
                        </div>
                        {debugMode && <p className="mt-2 text-red-500">调试模式已开启，可以穿墙</p>}
                        {showVictory && (
                            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                                <div className="bg-white p-8 rounded-xl shadow-lg text-center">
                                    <h2 className="text-3xl font-bold mb-4">恭喜你！</h2>
                                    <p className="text-xl mb-6">你成功走出了迷宫！</p>
                                    <button 
                                        onClick={() => {
                                            setShowVictory(false);
                                            generateMaze();
                                        }} 
                                        className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition duration-300"
                                    >
                                        再玩一次
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                );
            };



            const TicTacToe = () => {
                const [board, setBoard] = useState(Array(9).fill(null));
                const [winner, setWinner] = useState(null);
                const [isThinking, setIsThinking] = useState(false);

                const calculateWinner = (squares) => {
                    const lines = [
                        [0, 1, 2], [3, 4, 5], [6, 7, 8],
                        [0, 3, 6], [1, 4, 7], [2, 5, 8],
                        [0, 4, 8], [2, 4, 6]
                    ];
                    for (let i = 0; i < lines.length; i++) {
                        const [a, b, c] = lines[i];
                        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
                            return squares[a];
                        }
                    }
                    return null;
                };

                const minimax = (squares, depth, isMaximizing) => {
                    const winner = calculateWinner(squares);
                    if (winner === 'X') return -10 + depth;
                    if (winner === 'O') return 10 - depth;
                    if (squares.every(s => s !== null)) return 0;

                    if (isMaximizing) {
                        let bestScore = -Infinity;
                        for (let i = 0; i < squares.length; i++) {
                            if (squares[i] === null) {
                                squares[i] = 'O';
                                let score = minimax(squares, depth + 1, false);
                                squares[i] = null;
                                bestScore = Math.max(score, bestScore);
                            }
                        }
                        return bestScore;
                    } else {
                        let bestScore = Infinity;
                        for (let i = 0; i < squares.length; i++) {
                            if (squares[i] === null) {
                                squares[i] = 'X';
                                let score = minimax(squares, depth + 1, true);
                                squares[i] = null;
                                bestScore = Math.min(score, bestScore);
                            }
                        }
                        return bestScore;
                    }
                };

                const makeAIMove = (squares) => {
                    let bestScore = -Infinity;
                    let bestMove;
                    for (let i = 0; i < squares.length; i++) {
                        if (squares[i] === null) {
                            squares[i] = 'O';
                            let score = minimax(squares, 0, false);
                            squares[i] = null;
                            if (score > bestScore) {
                                bestScore = score;
                                bestMove = i;
                            }
                        }
                    }
                    return bestMove;
                };

                const handleClick = (i) => {
                    if (winner || board[i] || isThinking) return;
                    const newBoard = board.slice();
                    newBoard[i] = 'X';
                    setBoard(newBoard);
                    
                    const playerWinner = calculateWinner(newBoard);
                    if (playerWinner) {
                        setWinner(playerWinner);
                        return;
                    }

                    if (newBoard.some(square => square === null)) {
                        setIsThinking(true);
                        setTimeout(() => {
                            const aiMove = makeAIMove(newBoard);
                            newBoard[aiMove] = 'O';
                            setBoard(newBoard);
                            const aiWinner = calculateWinner(newBoard);
                            if (aiWinner) {
                                setWinner(aiWinner);
                            }
                            setIsThinking(false);
                        }, 500); // 添加延迟，模拟AI思考
                    }
                };

                const renderSquare = (i) => (
                    <button 
                        className={`w-16 h-16 text-3xl font-bold bg-white border-2 border-yellow-400 rounded-md focus:outline-none transition-all duration-300 transform hover:scale-105 ${
                            board[i] === 'X' ? 'text-blue-500' : 'text-red-500'
                        } ${board[i] ? 'animate-pop-in' : 'hover:bg-yellow-100'}`}
                        onClick={() => handleClick(i)}
                        disabled={winner || isThinking}
                    >
                        {board[i]}
                    </button>
                );

                const resetGame = () => {
                    setBoard(Array(9).fill(null));
                    setWinner(null);
                };

                let status;
                if (winner) {
                    status = winner === 'X' ? '恭喜你赢了！' : 'AI 赢了！';
                } else if (board.every(square => square !== null)) {
                    status = '平局';
                } else {
                    status = isThinking ? 'AI 正在思考...' : '轮到你了 (X)';
                }

                return (
                    <div className="flex flex-col items-center bg-gradient-to-b from-yellow-300 to-yellow-100 p-4 rounded-2xl">
                        <h2 className="text-3xl font-bold mb-4 text-yellow-800">井字棋</h2>
                        <div className="mb-4 text-xl font-bold text-yellow-900">
                            {status}
                        </div>
                        <div className="grid grid-cols-3 gap-1 mb-4">
                            {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(i => renderSquare(i))}
                        </div>
                        <button 
                            onClick={resetGame}
                            className="px-4 py-2 bg-yellow-500 text-white text-lg font-bold rounded-full hover:bg-yellow-600 transition duration-300 transform hover:scale-105 focus:outline-none"
                        >
                            重新开始
                        </button>
                    </div>
                );
            };

            const DinosaurGame = () => {
                const canvasRef = useRef(null);
                const [gameOver, setGameOver] = useState(false);
                const [score, setScore] = useState(0);

                useEffect(() => {
                    const canvas = canvasRef.current;
                    const ctx = canvas.getContext('2d');
                    let animationFrameId;

                    const dinoImg = new Image();
                    dinoImg.src = 'https://svgur.com/i/11Aq.svg';

                    const cactusImg = new Image();
                    cactusImg.src = 'https://svgur.com/i/11Ar.svg';

                    let dinoY = canvas.height - 60;
                    let dinoJumping = false;
                    let dinoDy = 0;

                    let cactusX = canvas.width;

                    const jump = () => {
                        if (!dinoJumping) {
                            dinoJumping = true;
                            dinoDy = -15;
                        }
                    };

                    const animate = () => {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);

                        // Draw ground
                        ctx.fillStyle = '#f0f0f0';
                        ctx.fillRect(0, canvas.height - 20, canvas.width, 20);

                        // Update and draw dinosaur
                        if (dinoJumping) {
                            dinoY += dinoDy;
                            dinoDy += 1;
                            if (dinoY >= canvas.height - 60) {
                                dinoY = canvas.height - 60;
                                dinoJumping = false;
                            }
                        }
                        ctx.drawImage(dinoImg, 50, dinoY, 40, 60);

                        // Update and draw cactus
                        cactusX -= 5;
                        if (cactusX < -30) {
                            cactusX = canvas.width;
                            setScore(prevScore => prevScore + 1);
                        }
                        ctx.drawImage(cactusImg, cactusX, canvas.height - 60, 30, 60);

                        // Collision detection
                        if (
                            cactusX < 90 &&
                            cactusX + 30 > 50 &&
                            dinoY > canvas.height - 100
                        ) {
                            setGameOver(true);
                            return;
                        }

                        animationFrameId = requestAnimationFrame(animate);
                    };

                    animate();

                    const handleKeyDown = (e) => {
                        if (e.code === 'Space') {
                            e.preventDefault();
                            jump();
                        }
                    };

                    window.addEventListener('keydown', handleKeyDown);

                    return () => {
                        cancelAnimationFrame(animationFrameId);
                        window.removeEventListener('keydown', handleKeyDown);
                    };
                }, []);

                const restartGame = () => {
                    setGameOver(false);
                    setScore(0);
                };

                return (
                    <div className="flex flex-col items-center">
                        <h2 className="text-2xl font-bold mb-4">恐龙跳一跳</h2>
                        <p className="mb-2">得分: {score}</p>
                        <canvas
                            ref={canvasRef}
                            width={600}
                            height={300}
                            className="border border-gray-300"
                        />
                        {gameOver && (
                            <div className="mt-4">
                                <p className="text-xl font-bold mb-2">游戏结束</p>
                                <button
                                    onClick={restartGame}
                                    className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded"
                                >
                                    重新开始
                                </button>
                            </div>
                        )}
                        <p className="mt-2">按空格键跳跃</p>
                    </div>
                );
            };

            const WhackAMole = () => {
                const [score, setScore] = useState(0);
                const [timeLeft, setTimeLeft] = useState(30);
                const [moles, setMoles] = useState(Array(9).fill(false));
                const [gameStarted, setGameStarted] = useState(false);

                useEffect(() => {
                    let timer;
                    let moleTimer;
                    if (gameStarted && timeLeft > 0) {
                        timer = setInterval(() => {
                            setTimeLeft(prevTime => prevTime - 1);
                        }, 1000);

                        moleTimer = setInterval(() => {
                            setMoles(prevMoles => {
                                const newMoles = [...prevMoles];
                                const randomIndex = Math.floor(Math.random() * 9);
                                newMoles[randomIndex] = true;
                                setTimeout(() => {
                                    setMoles(prevMoles => {
                                        const newMoles = [...prevMoles];
                                        newMoles[randomIndex] = false;
                                        return newMoles;
                                    });
                                }, 800);
                                return newMoles;
                            });
                        }, 1000);
                    } else if (timeLeft === 0) {
                        setGameStarted(false);
                    }
                    return () => {
                        clearInterval(timer);
                        clearInterval(moleTimer);
                    };
                }, [gameStarted, timeLeft]);

                const startGame = () => {
                    setScore(0);
                    setTimeLeft(30);
                    setMoles(Array(9).fill(false));
                    setGameStarted(true);
                };

                const whackMole = (index) => {
                    if (moles[index] && gameStarted) {
                        setScore(prevScore => prevScore + 1);
                        setMoles(prevMoles => {
                            const newMoles = [...prevMoles];
                            newMoles[index] = false;
                            return newMoles;
                        });
                    }
                };

                return (
                    <div className="flex flex-col items-center bg-gradient-to-b from-green-200 to-green-400 p-4 rounded-3xl shadow-lg">
                        <h2 className="text-3xl font-bold mb-4 text-green-800 animate-bounce">打地鼠</h2>
                        <div className="mb-4 bg-white px-4 py-2 rounded-full shadow-md">
                            <span className="text-lg font-bold mr-4 text-green-600">得分: {score}</span>
                            <span className="text-lg font-bold text-red-500">时间: {timeLeft}s</span>
                        </div>
                        <div className="grid grid-cols-3 gap-3 mb-4 bg-green-300 p-3 rounded-xl shadow-inner">
                            {moles.map((mole, index) => (
                                <button
                                    key={index}
                                    className={`w-16 h-16 rounded-full focus:outline-none transition-all duration-200 transform hover:scale-105 ${
                                        mole ? 'bg-brown-500 animate-pulse' : 'bg-green-600'
                                    }`}
                                    onClick={() => whackMole(index)}
                                    disabled={!gameStarted}
                                >
                                    {mole && <span className="text-2xl">🐹</span>}
                                </button>
                            ))}
                        </div>
                        <button
                            onClick={startGame}
                            className={`px-6 py-2 text-lg font-bold rounded-full shadow-lg transition duration-300 transform hover:scale-105 focus:outline-none ${
                                gameStarted
                                    ? 'bg-gray-400 cursor-not-allowed'
                                    : 'bg-yellow-400 hover:bg-yellow-500 text-yellow-900'
                            }`}
                            disabled={gameStarted}
                        >
                            {gameStarted ? '游戏进行中' : '开始游戏'}
                        </button>
                    </div>
                );
            };
            const renderGameContent = () => {
                switch(selectedGame) {
                    case 'maze':
                        return <MazeGame />;
                    case 'tictactoe':
                        return <TicTacToe />;
                    case 'DinosaurGame':
                        return <DinosaurGame />;
                    case 'whackamole':
                        return <WhackAMole />;
                    default:
                        return null;
                }
            };

            const handleGameSelect = (gameId) => {
                setIsTransitioning(true);
                setTimeout(() => {
                    setSelectedGame(gameId);
                    setIsTransitioning(false);
                }, 300);
            };

            const handleReturnToList = () => {
                setIsTransitioning(true);
                setTimeout(() => {
                    setSelectedGame(null);
                    setIsTransitioning(false);
                }, 300);
            };

            return (
                <div className="bg-yellow-50 rounded-3xl shadow-lg p-4 max-w-2xl mx-auto">
                    <h2 className="text-3xl font-bold mb-6 text-center text-gray-800">
                        {selectedGame ? games.find(game => game.id === selectedGame).name : '———— 选择游戏 ————'}
                    </h2>
                    <div className={`transition-opacity duration-300 ${isTransitioning ? 'opacity-0' : 'opacity-100'}`}>
                        {!selectedGame ? (
                            <div className="grid grid-cols-2 gap-3">
                                {games.map(game => (
                                    <button
                                        key={game.id}
                                        onClick={() => handleGameSelect(game.id)}
                                        className="bg-white hover:bg-gray-100 text-gray-800 font-semibold py-6 px-4 rounded-xl shadow-md transition duration-300 ease-in-out transform hover:scale-105 flex flex-col items-center w-full"
                                    >
                                        <div className={`mb-3 ${game.color}`}>{game.icon}</div>
                                        <span className="text-lg">{game.name}</span>
                                    </button>
                                ))}
                            </div>
                        ) : (
                            <div>
                                <button
                                    onClick={handleReturnToList}
                                    className="mb-6 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full shadow-md transition duration-300 ease-in-out transform hover:scale-105"
                                >
                                    ← 返回
                                </button>
                                <div className="bg-white p-6 rounded-xl shadow-md">
                    {renderGameContent()}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            );
        }

        function RandomNumberGenerator() {
            const [min, setMin] = useState(1);
            const [max, setMax] = useState(100);
            const [result, setResult] = useState(null);
            const [error, setError] = useState('');
            const [isGenerating, setIsGenerating] = useState(false);

            const generateRandomNumber = () => {
                if (min > max) {
                    setError('最小值不能大于最大值');
                    return;
                }
                setError('');
                setIsGenerating(true);
                let current = min;
                const interval = setInterval(() => {
                    current = Math.floor(Math.random() * (max - min + 1)) + min;
                    setResult(current);
                }, 50);

                setTimeout(() => {
                    clearInterval(interval);
                    const finalResult = Math.floor(Math.random() * (max - min + 1)) + min;
                    setResult(finalResult);
                    setIsGenerating(false);
                }, 2000);
            };

            return (
                <div className="bg-gradient-to-br from-yellow-100 to-yellow-200 rounded-3xl shadow-lg p-8 space-y-6 max-w-md mx-auto">
                    <h2 className="text-3xl font-bold text-center text-gray-800">随机数生成器</h2>
                    <div className="flex space-x-4">
                        <div className="flex-1">
                            <label className="block text-sm font-medium text-gray-700 mb-1">最小值</label>
                            <input
                                type="number"
                                value={min}
                                onChange={(e) => setMin(parseInt(e.target.value))}
                                className="w-full px-3 py-2 bg-white rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
                            />
                        </div>
                        <div className="flex-1">
                            <label className="block text-sm font-medium text-gray-700 mb-1">最大值</label>
                            <input
                                type="number"
                                value={max}
                                onChange={(e) => setMax(parseInt(e.target.value))}
                                className="w-full px-3 py-2 bg-white rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
                            />
                        </div>
                    </div>
                    <button
                        onClick={generateRandomNumber}
                        disabled={isGenerating}
                        className={`w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-4 rounded-lg transition duration-300 ${isGenerating ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                        {isGenerating ? '生成中...' : '生成随机数'}
                    </button>
                    {error && <p className="text-red-500 text-center">{error}</p>}
                    {result !== null && (
                        <div className="text-center bg-white rounded-lg p-6 shadow-inner">
                            <p className="text-lg font-semibold text-gray-700 mb-2">生成的随机数：</p>
                            <p className={`text-5xl font-bold text-blue-600 transition-all duration-300 ${isGenerating ? 'animate-pulse' : ''}`}>
                                {result}
                            </p>
                        </div>
                    )}
                </div>
            );
        }


        function App() {
            const [mode, setMode] = useState('clock');
            const [prevMode, setPrevMode] = useState(null);
            const [isTransitioning, setIsTransitioning] = useState(false);
            const [theme, setTheme] = useState('default');

            const changeMode = (newMode) => {
                if (newMode !== mode && !isTransitioning) {
                    setIsTransitioning(true);
                    setPrevMode(mode);
                    setTimeout(() => {
                        setMode(newMode);
                        setTimeout(() => {
                            setPrevMode(null);
                            setIsTransitioning(false);
                        }, 500); // 等待浮现动画完成
                    }, 300); // 等待淡出动画完成
                }
            };

            const changeTheme = (newTheme) => {
                setTheme(newTheme);
                // 应用主题样式到根元素
                document.documentElement.className = `theme-${newTheme}`;
            };

            useEffect(() => {
                // 应用初始主题
                document.documentElement.className = `theme-${theme}`;
            }, []);

            const renderContent = (currentMode) => {
                let content;
                let containerClass = "component-container";
                switch(currentMode) {
                    case 'clock':
                        content = <Clock />;
                        containerClass += " narrow";
                        break;
                    case 'stopwatch':
                        content = <Stopwatch />;
                        containerClass += " narrow";
                        break;
                    case 'timer':
                        content = <Timer />;
                        containerClass += " narrow";
                        break;
                    case 'calculator':
                        content = <Calculator />;
                        containerClass += " calculator-wide";
                        break;
                    case 'writingpad':
                        content = <WritingPad />;
                        containerClass += " calculator-wide";
                        break;
                    case 'game':
                        content = <Game />;
                        containerClass += " calculator-wide";
                        break;
                    case 'randomnumber':
                        content = <RandomNumberGenerator />;
                        containerClass += " calculator-wide";
                        break;
                    default:
                        content = null;
                }
                return (
                    <div className={containerClass}>
                        {content}
                    </div>
                );
            };

            return (
                <div className={`app-container theme-${theme}`}>
                    <ModeSelector 
                        currentMode={mode} 
                        onModeChange={changeMode} 
                        currentTheme={theme}
                        onThemeChange={changeTheme}
                    />
                    <div className="content-area">
                        <div className="w-full relative">
                            {prevMode && (
                                <div className="absolute top-0 left-0 w-full fade-out">
                                    {renderContent(prevMode)}
                                </div>
                            )}
                            <div className={`${isTransitioning ? 'opacity-0' : 'float-in'} w-full`}>
                                {renderContent(mode)}
                            </div>
                        </div>
                    </div>
                </div>
            );
        }

        ReactDOM.render(<App />, document.getElementById('root'));
    </script>
</body>
</html>